package com.qhgrain.app.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.paas.base.modules.utils.lang.StringUtil;
import com.qhgrain.app.constant.UrlEnum;
import com.qhgrain.app.service.RoleService;
import com.qhgrain.app.service.UserService;
import com.qhgrain.app.util.ConfigUtil;
import com.qhgrain.app.util.ControllerUtil;
import com.qhgrain.app.vo.AppGroupVo;
import com.qhgrain.app.vo.PairVo;
import com.qhgrain.app.vo.User;
import com.qhgrain.gway.util.HttpUtil;

@Controller
@RequestMapping("/user")
public class UserController {
	private static Logger LOG = LoggerFactory.getLogger(UserController.class);
	private final String SERVICEURL = ConfigUtil.getProperties(UrlEnum.USER);
	private final String POSTSERVICEURL = ConfigUtil.getProperties(UrlEnum.POSITION);
	private final String UNITSERVICEURL = ConfigUtil.getProperties(UrlEnum.UNIT);

	@Autowired
	private RoleService roleService;
	@Autowired
	private UserService userService;

	/**
	 * 根据ID删除用户
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping("/deleteByIds")
	@ResponseBody
	public JSONObject deleteByIds(Model model,  String ids,  String status) {

		JSONObject result = new JSONObject();
		if (StringUtil.isBlank(ids) || StringUtil.isBlank(status)) {
			result.put("code", "fail");
			result.put("msg", "用户id和状态不能为空");
		} else {

			try {
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("ids", ids);
				
				paramMap.put("status", status);
				String vo = HttpUtil.postFormParams(SERVICEURL,"/user/updateStatusByIds", paramMap);
				JSONObject voJson = JSONObject.parseObject(vo);
				if ("1".equals(voJson.getString("state"))) {
					result.put("code", "success");
					result.put("msg", "成功");
				} else {
					result.put("code", "fail");
					result.put("msg", "系统出错，删除失败!");
					LOG.error("删除用户,api失败..."
							+ voJson.getString("exceptionMsg"));
				}
			} catch (Exception e) {
				LOG.error("删除用户，系统出错...." + e.getStackTrace());
				result.put("code", "fail");
				result.put("msg", "系统出错");
			}
		}

		return result;
	}

	/**
	 * 获取所有用户
	 * 
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value = "/list")
	public String queryUsers() throws Exception {
		
		return "user/user_list";
	}
	@RequestMapping(value = "/list/table")
	public String queryUsersForTable(HttpServletRequest request,Model model, String pageNo, String pageSize,User user) throws Exception{
		int pageNum = StringUtil.isNotBlank(pageNo)?Integer.parseInt(pageNo):1;
		int size = StringUtil.isNotBlank(pageSize)?Integer.parseInt(pageSize):10;
		ControllerUtil.getSetParameters(request);
		model.addAttribute("pageBean", this.userService.queryPage(user.getUserName(), user.getLoginName(), user.getUnitId(), user.getUnitName(), user.getPostId(), user.getPostName(), user.getStatus(), pageNum, size));
		
		return "user/user_list_table";
	}
	/**
	 * 跳转 编辑/修改 用户页面
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/goEdit")
	public String goEdit(String userId,String currentPage,String pageSize, Model model) {
		JSONObject user = new JSONObject();
		if (!StringUtil.isBlank(userId)) {
			Map<String, String> params = new HashMap<String, String>();
			params.put("userId", userId);
			try {
				String jsonstr = HttpUtil.get(SERVICEURL + "/user/getUserById",
						params);
				JSONObject voJson = JSONObject.parseObject(jsonstr);
				if ("1".equals(voJson.getString("state"))) {
					user = voJson.getJSONObject("data");

				} else {
					LOG.error("编辑用户，从api获取对象信息失败..."
							+ voJson.getString("exceptionMsg"));
				}
			} catch (Exception e) {
				LOG.error(e.getMessage());
			}

		}
		model.addAttribute("currentPage", currentPage);
		model.addAttribute("pageSize", pageSize);
		model.addAttribute("user", user);
		return "/user/user_edit";
	}

	/**
	 * 
	 * 2016年3月29日 下午8:09:49
	 * 
	 * @tags 保存用户
	 * @author zhaoyq
	 */
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject save(Model model, User user) {
		JSONObject result = new JSONObject();
		try {
			if (user == null) {
				result.put("code", "fail");
				result.put("msg", "请确保数据填写完整");
			} else {
				String loginName = user.getLoginName();
				String userName = user.getUserName();
				String unitName = user.getUnitName();
				String postName = user.getPostName();
				String unitId = user.getUnitId();
				String postId = user.getPostId();
				if (StringUtil.isBlank(loginName)
						|| StringUtil.isBlank(userName)) {
					result.put("code", "fail");
					result.put("msg", "用户名或登录名不能为空");
				} else {
					String vo;
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("loginName", loginName);
					map.put("userName", userName);
					map.put("unitName", unitName);
					map.put("postName", postName);
					map.put("unitId", unitId);
					map.put("postId", postId);
					map.put("status", user.getStatus());
					if (StringUtil.isBlank(user.getUserId())) {
						// 新增
						vo = HttpUtil.postFormParams(SERVICEURL, "/user/add",
								map);
					} else {
						// 修改
						map.put("userId", user.getUserId());
						vo = HttpUtil.postFormParams(SERVICEURL, "/user/edit",
								map);
					}
					JSONObject voJson = JSONObject.parseObject(vo);
					if ("1".equals(voJson.getString("state"))) {
						result.put("code", "success");
						result.put("msg", "成功");
					} else if("0".equals(voJson.getString("state"))){
						result.put("code", "fail");
						result.put("msg", "系统出错，操作失败!");
						LOG.error("保存用户,api失败..."
								+ voJson.getString("exceptionMsg"));
					}else{
						result.put("code", "retry");
						result.put("msg", voJson.getString("exceptionMsg"));
					}
				}
			}

		} catch (Exception e) {
			LOG.error("保存用户系统出错。。。" + e.getMessage());
		}
		return result;
	}

	/**
	 * 根据ID获取用户
	 * 
	 * @param userId
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping(value = "/getUserById/{userId}")
	public String getUserById(@PathVariable String userId, Model model) throws IOException {
		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("userId", userId);
		String vo = HttpUtil.get(SERVICEURL + "/user/deleteByIds", paramMap);
		JSONObject voJson = JSONObject.parseObject(vo);
		// User user = userService.getUserById(userId);
		model.addAttribute("user", voJson);
		return "user/user_view";
	}

	/**
	 * 给用户赋角色
	 * 
	 * @param roleIds
	 * @param userId
	 * @return
	 */
	@RequestMapping("/addRoles")
	public JSONObject addRoles(String[] roleIds, String userId) {
		JSONObject result = new JSONObject();
		if (StringUtil.isBlank(userId)) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("userId", userId);
			map.put("roleIds", roleIds);
			try {
				String jsonstr = HttpUtil.postFormParams(SERVICEURL,
						"/user/addRoles", map);
				JSONObject voJson = JSONObject.parseObject(jsonstr);
				if ("1".equals(voJson.getString("state"))) {
					result.put("code", "success");
					result.put("msg", "成功");

				} else {
					result.put("code", "fail");
					result.put("msg", "系统出错，操作失败!");
					LOG.error("给用户赋角色失败..." + voJson.getString("exceptionMsg"));
				}
			} catch (Exception e) {
				LOG.error(e.getMessage());
			}

		}
		return result;
	}

	/**
	 * 获取所有岗位
	 * 
	 * @return
	 */
	@RequestMapping(value = "/getPost", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String getPost() {
		JSONArray result = new JSONArray();
		String jsonStr = "";
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			String jsonstr = HttpUtil.postFormParams(POSTSERVICEURL,
					"/position/selectPosition", map);
			JSONObject obj = JSONObject.parseObject(jsonstr);
			if (obj != null) {
				result = obj.getJSONArray("data");
				jsonStr = result.toJSONString();
			}
		} catch (Exception e) {
			LOG.error(e.getMessage());
		}

		return jsonStr;
	}

	/**
	 * 获取所有组织机构
	 * 
	 * @return
	 */
	@RequestMapping(value = "/getUnit", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String getUnit() {
		JSONArray result = new JSONArray();
		String jsonStr = "";
		HashMap<String, Object> map = new HashMap<String, Object>();
		
		try {
			//获取当前用户所在及其子机构,admin用户获取全部
			String currentUserLoginName = IndexController.getLoginName();
			if(StringUtil.isNotBlank(currentUserLoginName) && !"admin".equals(currentUserLoginName)){
			String currentUserUnitId = this.userService.findByLoginName(currentUserLoginName).getUnitId();
			map.put("currentUserUnitId", currentUserUnitId);
			}
			String jsonstr = HttpUtil.postFormParams(UNITSERVICEURL,
					"/iunitservice/queryUnit", map);
			JSONObject obj = JSONObject.parseObject(jsonstr);
			if (obj != null) {
				result = obj.getJSONArray("data");
				jsonStr = result.toJSONString();
			}
		} catch (Exception e) {
			LOG.error(e.getMessage());
		}

		return jsonStr;
	}

	/**
	 * 获取用户未拥有角色
	 * 
	 * @return
	 */
	@RequestMapping(value = "/getRoses", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject getRoses(Model model,String pageNo, String pageSize, String roleName,String  roleType,String userId) {
		JSONObject result = new JSONObject();
		try {
			//所有角色
			JSONArray allRolesArray = this.roleService.getAll(null);
			//用户拥有角色
			JSONArray userRoleArray =  roleService.getUserRoses(userId);
			//未拥有角色
			List<JSONObject> noSelectRole = getNoSelectRoles(allRolesArray,userRoleArray);
			result.put("right", noSelectRole);
			result.put("left", userRoleArray);
			
		} catch (Exception e) {
			LOG.error("用户赋角色，系统出错....",e);
		}
		return result;
	}

	/**
	 * 获取用户拥有的角色
	 */

	@RequestMapping(value = "/getUserRoses", method = RequestMethod.POST)
	@ResponseBody
	public JSONArray getUserRoses(String userId) {
		JSONArray result = new JSONArray();
		try {
			result = roleService.getUserRoses(userId);
		} catch (Exception e) {
			LOG.error(e.getMessage());
		}
		
		return result;
	}

	public List<JSONObject> getNoSelectRoles(JSONArray allRoles,JSONArray userRoles){

		List<JSONObject> list = new ArrayList<JSONObject>();
		if(allRoles == null || userRoles == null ){
			return list;
		}
		boolean isSelected = false;
		JSONObject aj;
		JSONObject uj;
		for(Object p : allRoles){
			aj = (JSONObject)p;
			isSelected = false;
			for(Object p2 : userRoles){
				uj = (JSONObject)p2;
				if(aj.get("id").equals(uj.get("id"))){
					isSelected = true;
					break;
				}
			}
			if(!isSelected){
				list.add(aj);
			}
		}
		return list;
	
	}
	/**
	 * 更新用户拥有的角色
	 * 先删除原来拥有的角色，再批量添加新的角色列表
	 */
	@RequestMapping(value = "/saveUserRoses", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject saveUserRoses(String userId,String roleIds) {
		JSONObject result = new JSONObject();
		boolean successd = false;
		try {
			//去重复
			roleIds = com.qhgrain.app.util.StringUtils.getNoRepeatStr(roleIds);
			successd = roleService.saveUserRoses(userId,roleIds);
			if(!successd){
				result.put("code", "fail");
				result.put("msg", "系统出错，操作失败");
			}else{
				result.put("code", "success");
				result.put("msg", "成功");
			}
		} catch (Exception e) {
			LOG.error(e.getMessage());
		}

		return result;
	}
	
	@RequestMapping(value = "/isExist", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject isExist(String loginName) {
		JSONObject result = new JSONObject();
		boolean successd = false;
		try {
			successd = userService.isExist(loginName);
			if(!successd){
				result.put("code", "success");
			}else{
				result.put("code", "fail");
			}
		} catch (Exception e) {
			result.put("code", "fail");
			LOG.error(e.getMessage());
		}
		
		return result;
	}

	/**
	 * 获取用户拥有的应用群组
	 */
	@RequestMapping(value = "/getUserAppGroups", method = RequestMethod.POST)
	@ResponseBody
	public String getUserAppGroups(String userId) {
		String result = "";
		try {
			List<AppGroupVo> userGroups = userService.queryByUserId(userId);
			result = JSONArray.toJSONString(userGroups);
		} catch (Exception e) {
			LOG.error(e.getMessage());
		}
		return result;
	}
	/**
	 * 获取用户未拥有的应用群组
	 */
	@RequestMapping(value = "/getUserNoAppGroups", method = RequestMethod.POST)
	@ResponseBody
	public String getUserNoAppGroups(String userId) {
		String result = "";
		try {
			List<AppGroupVo> userGroups = userService.queryByUserId(userId);
			List<AppGroupVo> allGroups = userService.queryByUserId(null);
			List<PairVo> noGroups = findNoSelectedApp(userGroups,allGroups);
			result = JSONArray.toJSONString(noGroups);
		} catch (Exception e) {
			LOG.error(e.getMessage());
		}
		return result;
	}
	private List<PairVo> findNoSelectedApp(List<AppGroupVo> selectedAppList,
			List<AppGroupVo> allAppList) {
		List<PairVo> list = new ArrayList<PairVo>();
		if(allAppList == null || selectedAppList == null ){
			return list;
		}
		boolean isSelected = false;
		for(AppGroupVo p : allAppList){
			isSelected = false;
			for(AppGroupVo p2 : selectedAppList){
				if(p.getId().equals(p2.getId())){
					isSelected = true;
					break;
				}
			}
			if(!isSelected){
				list.add(new PairVo(p.getId(), p.getName()));
			}
		}
		return list;
	}
	
	/**
	 * 更新用户拥有的应用群组
	 * 先删除原来拥有的应用群组，再批量添加新的应用群组列表
	 */
	@RequestMapping(value = "/saveUserAppGroups", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject saveUserAppGroups(String userId,String groupIds) {
		JSONObject result = new JSONObject();
		boolean successd = false;
		try {
			//去重复
			groupIds = com.qhgrain.app.util.StringUtils.getNoRepeatStr(groupIds);
			successd = userService.postUserAppGroups(userId, groupIds);
			if(!successd){
				result.put("code", "fail");
				result.put("msg", "系统出错，操作失败!");
			}else{
				result.put("code", "success");
				result.put("msg", "成功");
			}
		} catch (Exception e) {
			LOG.error(e.getMessage());
		}

		return result;
	}
}
